package com.mapler.ui;

import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.awt.Color;
import java.net.URL;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 *
 * @author none
 */
public class AccountViewUI extends javax.swing.JPanel {

    private javax.swing.JButton jButtonUpdate;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JTable jTableAccount;
    private javax.swing.JTextField usernameUI;
    private javax.swing.JTextField passwordUI;
    private String[] COLUMNS = {"ID", "Username", "Password"};
    private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0);
    private String username;
    private String password;
    private String recordId;
    
    private static Logger log = Logger.getLogger(AccountViewUI.class);
    public AccountViewUI() {
        initComponents();
    }

    public AccountViewUI(String username, String password) {
        this.username = username;
        this.password = password;
        initComponents();
    }

    private void initComponents() {
        usernameUI = new javax.swing.JTextField();
        passwordUI = new javax.swing.JTextField();
        jButtonUpdate = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabelMessage = new javax.swing.JLabel();
        javax.swing.JScrollPane jScrollPane2 = new javax.swing.JScrollPane();
        jTableAccount = new javax.swing.JTable(model);
        jTableAccount.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                int row = jTableAccount.rowAtPoint(e.getPoint());
                int col = jTableAccount.columnAtPoint(e.getPoint());
                setRecordId(jTableAccount.getValueAt(row, 0).toString());
                usernameUI.setText(jTableAccount.getValueAt(row, 1).toString());
                passwordUI.setText(jTableAccount.getValueAt(row, 2).toString());

                //System.out.println(row + ":" + col + ": Value in the cell clicked:" + jTableAccount.getValueAt(row, col).toString());
            }
        });

        jButtonUpdate.setText("Update");
        jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionUpdateHandler(evt);
            }
        });

        jButtonDelete.setText("Delete");
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionDeleteHandler(evt);
            }
        });

        jLabel1.setText("Username");
        jLabel2.setText("Password");

        jScrollPane2.setViewportView(jTableAccount);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(usernameUI, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jButtonUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonDelete))
                .addComponent(passwordUI, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addComponent(jLabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 519, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 55, Short.MAX_VALUE)))
                .addContainerGap())
                .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(usernameUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1)
                .addComponent(passwordUI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButtonUpdate)
                .addComponent(jButtonDelete))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    }

    private void actionUpdateHandler(java.awt.event.ActionEvent evt) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<AccountRequest>");
            request.append("<id>").append(this.getRecordId()).append("</id>");
            request.append("<username>").append(this.getUsername()).append("</username>");
            request.append("<password>").append(this.getPassword()).append("</password>");
            request.append("<rUsername>").append(this.usernameUI.getText()).append("</rUsername>");
            request.append("<rPassword>").append(this.passwordUI.getText()).append("</rPassword>");
            request.append("</AccountRequest>");

            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=userAccount/updateAccount&request=" + request.toString();
            
            String response = HttpHelper.post(new URL(uri), "");
            System.out.println("response :::" + response);
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("AccountResponse/errorcode");
            String msg = document.valueOf("AccountResponse/message");
            if (errorCode.equalsIgnoreCase("000")) {
                this.jLabelMessage.setBackground(Color.red);
            } else {
                this.getAccounts();
                this.jLabelMessage.setBackground(Color.black);
            }
            this.jLabelMessage.setText(msg);
        } catch (Exception ex) {
            this.jLabelMessage.setText("Error "+ex.getMessage());
            log.debug("Error "+ex);
        }
    }

    private void actionDeleteHandler(java.awt.event.ActionEvent evt) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<AccountRequest>");
            request.append("<id>").append(this.getRecordId()).append("</id>");
            request.append("<username>").append(this.getUsername()).append("</username>");
            request.append("<password>").append(this.getPassword()).append("</password>");
            request.append("<rUsername>").append(this.usernameUI.getText()).append("</rUsername>");
            request.append("<rPassword>").append(this.passwordUI.getText()).append("</rPassword>");
            request.append("</AccountRequest>");
            
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=userAccount/deleteAccount&request=" + request.toString();
            //System.out.println("::::::::::::" + uri);

            String response = HttpHelper.post(new URL(uri), "");

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("AccountResponse/errorcode");
            String msg = document.valueOf("AccountResponse/message");
            if (errorCode.equalsIgnoreCase("000")) {
                this.jLabelMessage.setBackground(Color.red);
            } else {
                this.getAccounts();
                this.jLabelMessage.setBackground(Color.black);
            }
            this.jLabelMessage.setText(msg);
        } catch (Exception ex) {
            this.jLabelMessage.setText("Error "+ex.getMessage());
            log.debug("Error "+ex);
        }
    }

    private void clearModel() {
        for (int i = model.getRowCount() - 1; i >= 0; i--) {
            model.removeRow(i);
        }
        jTableAccount.repaint();            
    }

    public void getAccounts() {
        try {
            this.clearModel();
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=userAccount/getAccounts&username="
                    + this.getUsername() + "&password=" + this.getPassword();
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("AccountResponse/errorcode");
            System.out.println(":::::::::" + errorCode);
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/AccountResponse/accounts/account");
                for (Node node : list) {
                    Object[] row = new Object[3];
                    row[0] = node.valueOf("id");
                    row[1] = node.valueOf("name");
                    row[2] = node.valueOf("password");
                    model.addRow(row);
                }
            } else {
                String message = document.valueOf("AccountResponse/message");
                this.jLabelMessage.setText(message);
            }
        } catch (Throwable ex) {
            this.jLabelMessage.setText("Error "+ex.getMessage());
            log.debug("Error "+ex);
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRecordId() {
        return recordId;
    }

    public void setRecordId(String recordId) {
        this.recordId = recordId;
    }
}
